﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.Users;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.Users
{
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, APIResult<User>>
    {
        private readonly IBaseRepository<User> userrReppos;
        private readonly IMapper mapper;

        public AddUserCommandHandler(IBaseRepository<User> userrReppos,IMapper mapper)
        {
            this.userrReppos = userrReppos;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<User>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            
                APIResult<User> result = new APIResult<User>();
           var data=mapper.Map<User>(request);
          var usesnum=  userrReppos.GetAllAsync().Result.FirstOrDefault(p=>p.UserName==request.UserName);
            if (usesnum==null) {
                await userrReppos.Add(data);
                result.data = data;

                result.Code = APIEnum.添加成功;
                result.Msg = APIEnum.添加成功.ToString();
            }
            else
            {
                result.data = data;
                result.Code = APIEnum.添加失败;
                result.Msg = APIEnum.添加失败.ToString();
            }
       
            
            return await Task.FromResult(result);
        }
    }
}
